package com.caterina.resources;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Timer;

public class CAnimator implements Runnable {
	public CAnimator(String baseUrl,JLabel label,int fps){
		this(baseUrl,label,fps,0,CAnimatorMode.NORMAL_ANIMATION);
	}
	public CAnimator(String baseUrl,JLabel label,int fps,int scaling){
		this(baseUrl,label,fps,scaling,CAnimatorMode.NORMAL_ANIMATION);
	}
	public CAnimator(String baseUrl,JLabel label,int fps,int scaling,CAnimatorMode mode){
			this.label=label;
			this.fps=fps;
			this.animate=true;
			this.animationMode=mode;
			this.load(baseUrl,scaling);
		}
	
		private void load(String baseUrl,int scaling){
			File folder=new File(CPaths.ConvertUrl(baseUrl));
			this.frames=new ArrayList<ImageIcon>();
			if (folder.isDirectory()&&!loadByCache(baseUrl+scaling)){
				for(File fl:folder.listFiles(new FilenameFilter() {
					public boolean accept(File arg0, String arg1) {return arg1.endsWith(".jpg");}
				})){
					ImageIcon tempImg=new ImageIcon(fl.getAbsolutePath());
					Image img=tempImg.getImage().getScaledInstance(tempImg.getIconWidth()+scaling, 
							tempImg.getIconHeight()+scaling,Image.SCALE_SMOOTH );
					frames.add(new ImageIcon(img));
				}
				ArrayList<ImageIcon> cacheFrames=new ArrayList<ImageIcon>();
				cacheFrames.addAll(frames);
				cache.put(baseUrl+scaling, cacheFrames);
			}
		}
		
		private boolean loadByCache(String path){
			if(cache.get(path)!=null){
				this.frames.addAll(cache.get(path));
				return true;
			}
			else return false;
		}
		
		public void stopAnimation(){
			this.animate=false;
		}
		@Override
		public void run() {
			timer = new Timer(1000/fps, new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					if (animate){
						label.setIcon(frames.get(getNextI()));
						label.repaint();
					}else timer.stop();
				}
			});
			timer.start();
		}
		private int getNextI(){
			switch (animationMode){
				case LOOP_ANIMATION:{
					if (i<frames.size()-2)return i++;
					else return i=0;
				}
				case NORMAL_ANIMATION:{
					if (i<frames.size()-2)return i++;
					else {timer.stop(); return i-=1;}
				}
				case LOOP_REVERSE_ANIMATION:{
					return i;
				}
				default: return i;
			}
			
			
		}
		/**
		 * @author   Marco
		 */
		public enum CAnimatorMode{/**
		 */
		LOOP_ANIMATION,/**
		 */
		NORMAL_ANIMATION,/**
		 */
		LOOP_REVERSE_ANIMATION}
		public boolean toHigh;
		public CAnimatorMode animationMode;
		private int fps;
		private boolean animate;
		private int i;
		private JLabel label;
		private static HashMap <String,ArrayList<ImageIcon>>cache=new HashMap <String,ArrayList<ImageIcon>>();
		private ArrayList<ImageIcon> frames;
		private Timer timer;
}
